// 数据库搜索管理器
class DBSearchManager {
    constructor() {
        this.apiClient = new ApiClient();
        this.currentResults = null;
        this.init();
        this.initializeEventListeners();
    }

    initializeEventListeners() {
        // 初始化事件监听器
        console.log('DBSearchManager event listeners initialized');
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    handleFileClick(element) {
        const filePath = element.getAttribute('data-file-path');
        if (filePath) {
            this.showFileContent(filePath);
        }
    }

    init() {
        this.bindEvents();
    }

    bindEvents() {
        // 搜索按钮
        const searchBtn = document.getElementById('db-search-btn');
        if (searchBtn) {
            searchBtn.addEventListener('click', () => this.searchFiles());
        }

        // 清空结果按钮
        const clearBtn = document.getElementById('db-search-clear-btn');
        if (clearBtn) {
            clearBtn.addEventListener('click', () => this.clearResults());
        }

        // 关闭文件内容按钮
        const closeContentBtn = document.getElementById('db-search-close-content-btn');
        if (closeContentBtn) {
            closeContentBtn.addEventListener('click', () => this.hideFileContent());
        }

        // 回车键搜索
        const patternInput = document.getElementById('db-search-pattern');
        if (patternInput) {
            patternInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.searchFiles();
                }
            });
        }

        const pathInput = document.getElementById('db-search-path');
        if (pathInput) {
            pathInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.searchFiles();
                }
            });
        }
    }

    async searchFiles() {
        const pattern = document.getElementById('db-search-pattern').value.trim();
        const searchPath = document.getElementById('db-search-path').value.trim();

        // 验证输入 - 搜索关键词现在是非必填的
        // 如果没有输入关键词，将返回所有索引过的目录结构

        try {
            this.showLoading();
            this.hideError();

            // 构建请求数据
            const requestData = {
                pattern: pattern,
                search_path: searchPath || ''
            };

            console.log('Searching files with data:', requestData);

            // 发送搜索请求
            const response = await fetch('/api/v1/directory-tree/db-search', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            
            if (!data.success) {
                throw new Error(data.message || '搜索失败');
            }

            this.currentResults = data.data;
            this.renderSearchResults(data.data);

        } catch (error) {
            console.error('搜索文件失败:', error);
            this.showError('搜索失败: ' + error.message);
        } finally {
            this.hideLoading();
        }
    }

    renderSearchResults(data) {
        const resultsContainer = document.getElementById('db-search-results');
        const treeContainer = document.getElementById('db-search-tree-container');
        const statsElement = document.getElementById('db-search-stats');
        const pattern = document.getElementById('db-search-pattern').value.trim();

        if (!data || !data.root) {
            this.showError('没有找到匹配的文件');
            return;
        }

        // 显示统计信息
        if (statsElement) {
            if (pattern) {
                statsElement.textContent = `找到 ${data.filtered_files} 个文件，共 ${data.total_dirs} 个目录，耗时 ${data.took}ms`;
            } else {
                statsElement.textContent = `显示所有索引目录，共 ${data.filtered_files} 个文件，${data.total_dirs} 个目录，耗时 ${data.took}ms`;
            }
        }

        // 渲染目录树
        if (treeContainer) {
            treeContainer.innerHTML = this.renderTreeNode(data.root, 0);
        }

        // 显示结果容器
        if (resultsContainer) {
            resultsContainer.classList.remove('hidden');
        }

        console.log('搜索结果渲染完成:', data);
    }

    renderTreeNode(node, depth) {
        if (!node) return '';

        const indent = '  '.repeat(depth);
        const isFile = node.type === 'file';
        const icon = isFile ? 
            (node.is_indexed ? '<i class="fas fa-file text-green-600"></i>' : '<i class="fas fa-file text-gray-400"></i>') :
            '<i class="fas fa-folder text-blue-600"></i>';
        
        const sizeInfo = isFile ? ` <span class="text-xs text-gray-500">(${this.formatFileSize(node.size)})</span>` : '';
        const indexedBadge = isFile && node.is_indexed ? ' <span class="inline-block bg-green-100 text-green-800 text-xs px-2 py-1 rounded">已索引</span>' : '';
        
        // 为文件添加点击事件和样式 - 使用data属性存储路径，避免HTML编码问题
        const fileClickable = isFile ? 'cursor-pointer hover:bg-blue-50' : '';
        const fileDataPath = isFile ? `data-file-path="${this.escapeHtml(node.path)}"` : '';
        
        let html = `<div class="tree-node" style="margin-left: ${depth * 20}px;">
            <span class="tree-item flex items-center py-1 ${fileClickable}" ${fileDataPath} onclick="window.dbSearchManager.handleFileClick(this)">
                ${icon}
                <span class="ml-2 ${isFile ? 'text-gray-800 hover:text-blue-600' : 'font-medium text-blue-800'}">${this.escapeHtml(node.name)}</span>
                ${sizeInfo}
                ${indexedBadge}
            </span>`;

        // 如果有子节点，递归渲染
        if (node.children && node.children.length > 0) {
            html += '<div class="tree-children">';
            for (const child of node.children) {
                html += this.renderTreeNode(child, depth + 1);
            }
            html += '</div>';
        }

        html += '</div>';
        return html;
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
    }

    clearResults() {
        const resultsContainer = document.getElementById('db-search-results');
        const treeContainer = document.getElementById('db-search-tree-container');
        const patternInput = document.getElementById('db-search-pattern');
        const pathInput = document.getElementById('db-search-path');

        // 清空输入框
        if (patternInput) patternInput.value = '';
        if (pathInput) pathInput.value = '';

        // 隐藏结果
        if (resultsContainer) {
            resultsContainer.classList.add('hidden');
        }

        // 清空树容器
        if (treeContainer) {
            treeContainer.innerHTML = '<div class="text-gray-500 text-center py-8"><i class="fas fa-search text-4xl mb-2"></i><p>输入关键词开始搜索，或留空显示所有索引目录</p></div>';
        }

        this.currentResults = null;
        this.hideError();
    }

    showLoading() {
        const loadingElement = document.getElementById('db-search-loading');
        if (loadingElement) {
            loadingElement.classList.remove('hidden');
        }
    }

    hideLoading() {
        const loadingElement = document.getElementById('db-search-loading');
        if (loadingElement) {
            loadingElement.classList.add('hidden');
        }
    }

    showError(message) {
        const errorElement = document.getElementById('db-search-error');
        const errorMessageElement = document.getElementById('db-search-error-message');
        
        if (errorElement && errorMessageElement) {
            errorMessageElement.textContent = message;
            errorElement.classList.remove('hidden');
        }
    }

    hideError() {
        const errorElement = document.getElementById('db-search-error');
        if (errorElement) {
            errorElement.classList.add('hidden');
        }
    }

    async showFileContent(filePath) {
        try {
            console.log('Loading file content for:', filePath);
            
            // 确保路径是字符串类型
            if (typeof filePath !== 'string') {
                console.error('Invalid file path type:', typeof filePath, filePath);
                alert('无效的文件路径');
                return;
            }
            
            // 使用弹窗显示文件内容，类似文件检索功能
            if (window.modalManager) {
                // 使用相对路径，让服务器自动解析
                const relativePath = this.convertToRelativePath(filePath);
                console.log('Using relative path:', relativePath);
                
                // 检查转换后的路径是否有效
                if (!relativePath || relativePath.trim() === '') {
                    console.error('Failed to convert path to relative:', filePath);
                    alert('无法解析文件路径');
                    return;
                }
                
                // 调用弹窗管理器显示文件内容
                await window.modalManager.showFileContentModal(relativePath);
            } else {
                console.error('Modal manager not available');
                alert('弹窗管理器未初始化，无法显示文件内容');
            }

        } catch (error) {
            console.error('Failed to load file content:', error);
            alert(`加载文件内容失败: ${error.message}`);
        }
    }

    convertToRelativePath(absolutePath) {
        // 从绝对路径中提取相对路径
        // 例如：D:\2025年项目\技术类项目\go文件感知国产模型\test\测试知识 国资委监管制度\业绩考核和分配\xxx.md
        // 转换为：test/测试知识 国资委监管制度/业绩考核和分配/xxx.md
        
        console.log('Converting absolute path to relative:', absolutePath);
        
        // 检查路径是否有效
        if (!absolutePath || typeof absolutePath !== 'string') {
            console.error('Invalid absolute path:', absolutePath);
            return '';
        }
        
        // 如果路径已经被编码，先解码
        let cleanPath = absolutePath.trim();
        try {
            // 检查路径是否包含编码字符（%XX格式）
            if (cleanPath.includes('%')) {
                cleanPath = decodeURIComponent(cleanPath);
                console.log('Decoded path:', cleanPath);
            }
        } catch (error) {
            console.error('Error decoding path:', error);
            // 如果解码失败，继续使用原始路径
        }
        
        // 查找项目根目录标识
        const projectRootPattern = /go文件感知国产模型[\\\/]/;
        const match = cleanPath.match(projectRootPattern);
        
        if (match) {
            // 获取项目根目录之后的路径部分
            const afterProjectRoot = cleanPath.substring(match.index + match[0].length);
            // 确保路径分隔符统一为正斜杠
            const relativePath = afterProjectRoot.replace(/\\/g, '/');
            console.log('Converted to relative path:', relativePath);
            return relativePath;
        }
        
        // 如果没有匹配到项目根目录，尝试查找已知的索引目录
        const knownDirectories = [
            'test/', 'docs/', 'config/', 'internal/', 'cmd/', 'web/', 'tools/', 'scripts/'
        ];
        
        for (const dir of knownDirectories) {
            if (cleanPath.includes(dir)) {
                const dirIndex = cleanPath.indexOf(dir);
                const afterDir = cleanPath.substring(dirIndex);
                const relativePath = afterDir.replace(/\\/g, '/');
                console.log('Found known directory, converted to relative path:', relativePath);
                return relativePath;
            }
        }
        
        // 如果仍然没有找到合适的路径，尝试从路径中提取最后两级目录
        const pathParts = cleanPath.split(/[\\\/]/);
        if (pathParts.length >= 3) {
            const relativePath = pathParts.slice(-3).join('/');
            console.log('Fallback to last 3 path parts:', relativePath);
            return relativePath;
        } else if (pathParts.length >= 2) {
            const relativePath = pathParts.slice(-2).join('/');
            console.log('Fallback to last 2 path parts:', relativePath);
            return relativePath;
        }
        
        // 最后的备选方案：直接使用文件名
        const fileName = pathParts[pathParts.length - 1];
        console.log('Final fallback to filename:', fileName);
        return fileName;
    }

    hideFileContent() {
        const contentContainer = document.getElementById('db-search-file-content');
        if (contentContainer) {
            contentContainer.classList.add('hidden');
        }
        
        // 清空内容
        const contentText = document.getElementById('db-search-file-content-text');
        const pathElement = document.getElementById('db-search-current-file-path');
        
        if (contentText) {
            contentText.textContent = '';
        }
        
        if (pathElement) {
            pathElement.textContent = '';
        }
    }
}

// 当DOM加载完成时初始化
document.addEventListener('DOMContentLoaded', function() {
    window.dbSearchManager = new DBSearchManager();
    console.log('数据库搜索管理器初始化完成');
});